package com.ty.web;

import com.ty.bean.Student;
import com.ty.service.StudentService;
import com.ty.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 田野
 */
@WebServlet(urlPatterns = "/Educational/student/getStudentList")
public class GetStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、获取参数
        // 1.1 模糊查询条件的参数
        String stuname = req.getParameter("stuname");
        String stuno = req.getParameter("stuno");
        // String sex = req.getParameter("sex");
        System.out.println("class:GetStudentServlet.java" + req.getParameter("stuname"));
        System.out.println("class:GetStudentServlet.java" + req.getParameter("stuno"));
        System.out.println("class:GetStudentServlet.java" + req.getParameter("sex"));
        int sex = -1;
        if (req.getParameter("sex") != null){
            sex = Integer.parseInt(req.getParameter("sex"));
        }
        // 1.2 分页数据  limit 开始位置 显示条数
        // 页码值(这就是当前页码值)
        String pageIndex = req.getParameter("pageIndex");
        // 如果页面没有传入pageIndex的值，那么默认为查询第一页
        int index = (pageIndex == null?1:Integer.parseInt(pageIndex));

        // 2、调用service层方法
        StudentService service = new StudentServiceImpl();
        List<Student> students = service.getStudents(stuname, stuno, sex, index, 5);
        // 获取 总的页数=总条数%每页显示的条数>0?(总条数/每页显示的条数 + 1):总条数/每页显示的条数
        int total = service.total(stuname, stuno, sex);
        int totalPages = total%5 > 0 ?(total/5+1):total/5;

        // 3、跳转页面
        // 如果后台想给前台传数据，是一定要在后台存值的  pageContext request session application
        req.setAttribute("stulist", students);
        // 存储模糊查询条件
        req.setAttribute("stuname", stuname);
        req.setAttribute("stuno", stuno);
        req.setAttribute("sex", sex);
        // 存储分页数据
        req.setAttribute("index", index);
        req.setAttribute("size", 5);
        req.setAttribute("total", total);
        req.setAttribute("totalPages", totalPages);

        // 跳转页面中重定向会丢失request的数据，因此应该用转发
        req.getRequestDispatcher("list.jsp").forward(req, resp);

    }
}
